<?php

namespace App\Manage;


use App\Models\SiteConfig;
use App\Service\Base\Manage;
use Illuminate\Support\Facades\DB;

class SiteConfigManage extends Manage
{

    // 基本配置
    public function initialize()
    {
        parent::initialize();

        $this->model = 'SiteConfig';
    }

    // 配置查询
    public function getConfig()
    {
        $model = new SiteConfig();
        $list  = $model->isCache(true)->getConfig();

        return $list;
    }

    // 基本配置
    public function saveConfig()
    {
        // 参数
        $opt  = $this->option();
        $data = $opt->getData();
        $data = $this->filterNull($data);
        unset($data['module'], $data['controller'], $data['action']);
        if(empty($data)){
            return $this->_returnFail('请传递需要修改的数据！');
        }


        // 获取配置
        $model = new SiteConfig();
        $list  = $model->isCache(true)->get()->toArray();
        $list  = array_column($list, null, 'field');
        $table = 'site_config';


        // 保存数据
        DB::beginTransaction();
        try{
            foreach($data as $field => $val){
                $info = $list[$field] ?? [];
                // 添加
                if(empty($info)){
                    // 更新新数据
                    $setArr = ["field" => $field, "value" => $val];
                    $result = DB::table($table)->insert($setArr);
                    $errMsg = '保存配置信息失败！！';
                } else{
                    // 修改
                    $result = DB::table($table)->where(['id' => $info['id']])->update(["value" => $val]);
                    $errMsg = '修改原来的配置信息失败！！';
                }
                if($result === false){
                    throw  new \Exception($errMsg);
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->_returnFail($e->getMessage());
        }

        // 删除缓存
        $model->deleteCacheList($list);

        return true;
    }

}


